#include "TcpServer.hpp"
#include "protocol.hpp"
static void usage(const std::string& process)
{
    std::cout<<process<<" port "<<std::endl; 
}

static Response calculatorHelper(const Request &req)
{
    Response resp(0, 0, req._x, req._y, req._op);
    switch (req._op)
    {
    case '+':
        resp._result = req._x + req._y;
        break;
    case '-':
        resp._result = req._x - req._y;
        break;
    case '*':
        resp._result = req._x * req._y;
        break;
    case '/':
        if (0 == req._y)
            resp._code = 1;
        else
            resp._result = req._x / req._y;
        break;
    case '%':
        if (0 == req._y)
            resp._code = 2;
        else
            resp._result = req._x % req._y;
        break;
    default:
        resp._code = 3;
        break;
    }
    return resp;
}
void calculator(int sock)
{
    std::string inbuffer;
    while(true)
    {
        //接收客户端发来的请求
        bool res = Recv(sock,&inbuffer);
        //判断是否接收成功
        if(!res)
        {
            break;
        }
        //进行解包处理，保留有效载荷
        std::string package = Decode(inbuffer);
        //没有接收到完整报文，继续接收
        if(package.empty())
        {
            continue;
        }
        //接收成功
        logMessage(NORMAL, "%s", package.c_str());
        //对接收到的报文进行反序列化处理，方便计算
        Request req;
        req.Deserialized(package);

        //此时处理成功，进行计算
        Response resp = calculatorHelper(req);

        //计算完毕之后对计算结果进行序列化处理
        std::string respString =resp.Serialize();

        //进行协议定制
        respString = Encode(respString);
        std::cout<<respString<<std::endl;
        
        //发送协议定制好的信息
        Send(sock, respString);

    }
}
int main(int argc,char* argv[])
{
    if(argc!=2)
    {
        usage(argv[0]);
        exit(1);
    }
    uint16_t server_ip = atoi(argv[1]);
    TcpServer* server = new TcpServer(server_ip);
    server->BindService(calculator);
    server->start();
    return 0;
}